package cn.iocoder.yudao.module.system.api.translate;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.system.dal.redis.translate.TranslateRedisDAO;
import cn.iocoder.yudao.module.system.framework.translate.config.TranslateConfig;
import cn.iocoder.yudao.module.system.framework.translate.core.ITranslateClient;
import cn.iocoder.yudao.module.system.framework.translate.core.TranslateClientFactory;
import cn.iocoder.yudao.module.system.framework.translate.enums.TranslateChannelEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Description: 翻译api
 * Author: li
 * Date: 2024/2/20
 */
@Service
@Slf4j
public class TranslateApiImpl implements ITranslateApi {
    @Resource
    private TranslateConfig translateConfig;
    @Resource
    private TranslateClientFactory clientFactory;
    @Resource
    private TranslateRedisDAO translateRedisDAO;

    @Override
    public String translate(String text, String targetLanguage) {
        String translatedText = translateRedisDAO.get(text, targetLanguage);
        if (StrUtil.isNotEmpty(translatedText)) {
            log.info("翻译文本-使用缓存,  targetLanguage = {}, text = {}, translatedText = {}",
                    targetLanguage, text, translatedText);
            return translatedText;
        }

        final String channel = translateConfig.getChannel();
        final TranslateChannelEnum channelEnum = TranslateChannelEnum.getByCode(channel);
        final ITranslateClient client = clientFactory.getTranslateClient(channelEnum);

        translatedText = client.translate(text, targetLanguage);
        translateRedisDAO.set(text, targetLanguage, translatedText);
        log.info("翻译文本-使用API, channel = {}, targetLanguage = {}, text = {}, translatedText = {}",
                channel, targetLanguage, text, translatedText);

        return translatedText;
    }

}


